package flyweight;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

/**
 * 享元模式
 * 减少对象的创建，提高效率
 * 关注内外部状态，关注线程安全问题
 * 使系统逻辑复杂化
 * 多设计成单例模式
 */
public class ConnectionPool {
    private final Vector<Connection> pool;
    private final int poolSize=100;
    private final String url="jdbc:mysql://localhost:3306/test";
    private final String username="root";
    private final String password="root";
    private final String driverClassName="com.mysql.jdbc.Driver";
    public ConnectionPool() {
        pool=new Vector<>(poolSize);
        try {
            Class.forName(driverClassName);
            for (int i=0;i<poolSize;i++){
                Connection connection=DriverManager.getConnection(url,username,password);
                pool.add(connection);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    public synchronized Connection getConnection(){
        if (pool.size()>0){
            Connection connection=pool.get(0);
            pool.remove(connection);
            return connection;
        }
        else{
            return null;
        }
    }
    public synchronized void release(Connection connection){
        pool.add(connection);
    }
}
